import {
  ui
} from './ui';
import {
  ds
} from './data';
import {
  localData
} from './localData';

const DATA_NAME = 'userinfo'

export const users = {
  getUserInfo: async function () {
    return new Promise(resolve => {
      ds.cloudGetByOpenid('users', async res => {
        const _openid = res._openid
        if (res.result.data.length == 0) {
          const createTime = new Date().getTime()
          const addRes = await this.init(createTime) // { _id, errMsg }
          resolve({
            _id: addRes._id,
            role: 'custom',
            createTime,
            _openid
          })
          return
        }
        const info = res.result.data[0] || null
        localData.set(DATA_NAME, info)
        resolve(info)
      })
    })
  },
  getUser: async function () {
    return users.getUserInfo()
  },
  getUserByOpenid: async function (openid, field) {
    return new Promise((resolve, reject) => {
      const coll = ds.coll('users').where({
        _openid: ds.cmd.eq(openid)
      })
      return (field ? coll.field(field) : coll).get()
        .then(res => resolve(res.data[0]))
        .catch(err => reject(err))
    })
  },
  getUserById: async function (id, field) {
    return new Promise((resolve, reject) => {
      const coll = ds.coll('users').where({
        _id: ds.cmd.eq(id)
      })
      return (field ? coll.field(field) : coll).get()
        .then(res => resolve(res.data[0]))
        .catch(err => reject(err))
    })
  },
  init(createTime) {
    return ds.coll('users')
      .add({
        data: {
          role: "custom",
          createTime: createTime || new Date().getTime()
        }
      })
  },
  setLocalUserInfo: function (user) {
    localData.set(DATA_NAME, user)
  },
  getProfile: function (cb) {
    wx.getUserProfile({
      desc: '获取您的个人信息',
      success: (res) => {
        const userinfo = {
          personInfo: res.userInfo
        }
        localData.set(DATA_NAME, userinfo)
        if (cb) cb(res.userInfo)
      },
      fail: function (e) {

      }
    })
  },
  getOpenId: function (cb) {
    wx.cloud.callFunction({
      name: 'getOpenId',
      complete: res => {
        if (cb) cb(res.result)
      }
    })
  },
  getMobile: async function (event, cb) {
    const errMsg = event.detail.errMsg
    // 判断用户是否点击允许
    if (errMsg === "getPhoneNumber:ok") {
      const cloudId = event.detail.cloudID
      const cloudIdList = [cloudId]
      // 请求云函数
      const cloudFunRes = await wx.cloud.callFunction({
        name: "getMobile", // 云函数名
        data: {
          cloudIdList
        }
      })

      try {
        // console.log(cloudFunRes)
        const jsonStr = cloudFunRes.result.dataList?.[0].json
        const jsonData = jsonStr && JSON.parse(jsonStr)
        const phoneNumber = jsonData?.data.phoneNumber
        if (phoneNumber && cb) {
          cb(phoneNumber)
        } else {
          ui.toast(false, '获取手机号失败')
        }
      } catch (err) {
        ui.toast(false, '获取手机号失败')
        console.info(cloudFunRes)
        console.info(err)
      }
    }
  },
  getCachedUserInfo() {
    return localData.get(DATA_NAME);
  },
  isVip(user) {
    return user.vip == "1" || user.vip == true || user.vip == "true"
  },
  getRoleName(role) {
    const rname = {
      'admin': '管理员',
      'delivery': '配送员',
      'master': '店长',
      'custom': '客户'
    }
    return rname[role] ?? '未知角色'
  }
}